﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillData();
            }
            else
            {

            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            var dt = new DataTable();
            dt.Columns.Add(new DataColumn("Id"));
            dt.Columns.Add(new DataColumn("ProductName"));
            dt.Columns.Add(new DataColumn("ShortDesc"));
            dt.Columns.Add(new DataColumn("Remarks"));
            foreach (GridViewRow row in gv3.Rows)
            {
                var tempRow = dt.NewRow();
                tempRow["Id"] = GetVlaue(row.RowIndex, 0);
                tempRow["ProductName"] = GetVlaue(row.RowIndex, 1).Replace("&nbsp", "");
                tempRow["ShortDesc"] = GetVlaue(row.RowIndex, 2).Replace("&nbsp", "");
                tempRow["Remarks"] = GetVlaue(row.RowIndex, 3).Replace("&nbsp", "");
                dt.Rows.Add(tempRow);
            }
        }

        protected void gv3_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = GetVlaue(e.RowIndex, 0);
            var sql = string.Format("delete from products where id='{0}'",id);
            gv3.EditIndex = -1;
            FillData();
        }

        protected void gv3_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var id = GetVlaue(e.RowIndex, 0);
            var pname = GetVlaue(e.RowIndex, 1);
            var desc = GetVlaue(e.RowIndex, 2);
            var remarks = GetVlaue(e.RowIndex, 3);
            var sql = string.Format("update products set productname='{0}',shortdesc='{1}',remarks='{2}' where id='{3}'",pname,desc,remarks,id);
        }

        private string GetVlaue(int rowIndex, int colIndex)
        {
            var c = gv3.Rows[rowIndex].Cells[colIndex];
            var value = c.Controls.Count > 0 ? ((TextBox)c.Controls[0]).Text : c.Text;
            return value;
        }

        protected void gv3_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gv3.EditIndex = -1;
            FillData();
        }
        private void FillData()
        {
            var sql = "select * from Products";
            var dt = DbHelper.GetData(sql);
            gv3.DataSource = dt;
            gv3.DataBind();
        }

        protected void gv3_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gv3.EditIndex = e.NewEditIndex;
            FillData();
        }
    }
}